package com.wjk.cms.controller;

import com.alibaba.fastjson.JSONObject;
import com.wjk.cms.common.AuthControllerHelper;
import com.wjk.cms.common.Result;
import com.wjk.cms.pojo.Card;
import com.wjk.cms.pojo.User;
import com.wjk.cms.util.DateUtil;
import com.wjk.cms.util.RealnameUtil;
import com.wjk.cms.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WUGN
 * @des
 * @date 2021/9/13 11:12
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends AuthenticatedController {

    @Autowired
    private AuthControllerHelper authControllerHelper;

    @Autowired
    private UserService userService;

    @Autowired
    private CardService cardService;


    @Autowired
    private WxXcxService wxXcxService;

    /**
     * 修改手机号
     */
    @Transactional
    @PostMapping("/change-password")
    public Result changePhone(
            @RequestParam("password") String password // 验证码
    ) {
        log.info("请求参数 - /user/change-phone\n"
                + "[Body]" + "\n"
                + "password: " + password + "\n"
                );

        User currentUser = getCurrentUser();

        currentUser.setPassword(password);

        userService.save(currentUser);
        return Result.ok();
    }

    @PostMapping("/list")
    public Result list(
            @RequestParam(value = "keywords", required = false) String keywords, // 页码
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, // 页码
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize // 数
    ) {
        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("1")){
            return Result.error("非渠道商没有该权限");
        }

        String[] text = {"待审","审核通过","审核不通过"};
        List<User> list = userService.findChildren(currentUser.getId(),keywords,pageNo, pageSize);
        int totalReceive = 0;
        int totalDeal = 0;
        for (User user : list) {
            List<Card> allList = cardService.list(user.getId(), null, "", null, null,null,null,null, null);
            user.setReceiveNum(allList.size());
            user.setStatusText(text[Integer.parseInt(user.getStatus())]);
            totalReceive += user.getReceiveNum();
            List<Card> status1List = allList.stream().filter(card -> card.getStatus() == 1).collect(Collectors.toList());
            user.setDealNum(allList.size()-status1List.size());
            totalDeal+=user.getDealNum();

        }

        List<User> totallist = userService.findChildren(currentUser.getId(), keywords,-1, pageSize);
        JSONObject obj1 = new JSONObject();
        obj1.put("name","经销商总数");
        obj1.put("num",totallist.size());
        JSONObject obj2 = new JSONObject();
        obj2.put("name","卡领取总数");
        obj2.put("num",totalReceive);
        JSONObject obj3 = new JSONObject();
        obj3.put("name","卡成交总数");
        obj3.put("num",totalDeal);
        ArrayList<Object> tab = new ArrayList<>();
        tab.add(obj1);
        tab.add(obj2);
        tab.add(obj3);

        return Result.ok().add("data",list).add("tab",tab);
    }

    @PostMapping("/findUserByPhone")
    public Result findUserByPhone(@RequestParam("phone") String phone) {

        log.info("请求参数 - /user/findUserByPhone\n"
                + "phone: " + phone + "\n");
        User currentUser = getCurrentUser();
        User customer = userService.getByPhone(phone);
        if(customer ==null){
            return Result.error("用户未注册，不存在该用户！");
        }

        return Result.ok().add("user",customer);
    }

    @PostMapping("/info")
    public Result info(HttpServletRequest request) {
        User currentUser = getCurrentUser();
        return authControllerHelper.loadUserInfo(request, Result.ok(), currentUser, true);
    }



    @Transactional
    @PostMapping("/addSeller")
    public Result addSeller(
            User user
    ) {
        log.info("请求参数 - /user/addSeller\n"
                + "[Body]" + "\n"
                + "user: " + user + "\n"
        );

        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("1")){
            return Result.error("只有渠道商拥有权限添加");
        }

        if(StringUtils.isBlank(user.getPhone())){
            return Result.error("请填写手机号");
        }
        User byPhone = userService.getByPhone(user.getPhone());
        if(byPhone!=null){
            return Result.error("该手机号已被使用");
        }

        user.setType("2");
        user.setParentId(currentUser.getId());
        user.setStatus("0");
        user.setPassword("123456");
        userService.save(user);
        return Result.ok();
    }

    @Transactional
    @PostMapping("/edit")
    public Result edit(HttpServletRequest request,
            User user
    ) {
        log.info("请求参数 - /user/edit\n"
                + "[Body]" + "\n"
                + "user: " + user + "\n"
        );

        User currentUser = getCurrentUser();

        currentUser.setAddress(user.getAddress());
        currentUser.setPhone(user.getPhone());
        currentUser.setPassword(user.getPassword());
        currentUser.setName(user.getName());
        userService.save(currentUser);
        return authControllerHelper.loadUserInfo(request, Result.ok(), currentUser, true);
    }




}
